import { Component, OnInit, ViewChild } from '@angular/core';
import { ApiShipAddressService } from '../../../api/system/api-ship-address.service';
import { IShipAddress } from '../../../api/pojo/system/i-ship-address';
import { ShipAddressDetailModalComponent } from './parts/ship-address-detail-modal/ship-address-detail-modal.component';
import { NzNotificationService, NzModalService, NzTableComponent } from 'ng-zorro-antd';

@Component({
  selector: 'sda-ship-address',
  templateUrl: './ship-address.component.html',
  styleUrls: ['./ship-address.component.scss']
})
export class ShipAddressComponent implements OnInit {

  // 当前收货地址详情
  addressDetail: IShipAddress;

  addressList: IShipAddress[] = [];

  @ViewChild(ShipAddressDetailModalComponent)
  detailModal: ShipAddressDetailModalComponent;

  @ViewChild('AddressTable')
  addressTable: NzTableComponent;

  constructor(
    private apiService: ApiShipAddressService,
    private notification: NzNotificationService,
    private modal: NzModalService
  ) { }

  ngOnInit() {
    this.fetchAddressList();
  }

  fetchAddressList() {
    this.addressTable.nzLoading = true;
    this.apiService
      .getAddressList()
      .subscribe(res => {
        this.addressTable.nzLoading = false;
        this.addressList = res.dat.list;
      });
  }

  onAddAddress() {
    this.addressDetail = null;
    this.detailModal.show();
  }

  onRemoveItem(id: number, i: number) {
    this.modal.confirm({
      nzTitle: '系统提示',
      nzContent: '确定删除发货地址？',
      nzOnOk: () => {
        this.apiService
        .deleteAddress(id)
        .subscribe(res => {
          this.notification.success(res.msg, res.dat);
          this.addressList.splice(i, 1);
          this.addressList = [...this.addressList];
        });
      }
    });
  }

  onSelectItem(data: IShipAddress) {
    this.addressDetail = data;
    this.detailModal.show();

    // this.apiService
    //   .getAddressDetail(data.id)
    //   .subscribe(res => {
    //     this.addressDetail = res.dat.details
    //     this.detailModal.show();
    //   })
  }

  /**
   * 详情modal的关闭回调
   */
  onModalHide() {
    this.fetchAddressList();
    this.addressDetail = null;
  }

}
